
<template>
  <div  style=" ">
    <!--    忘记密码页面-->
    <div style="height: 100vh; overflow: hidden; position: relative;" :style="background">
      <!--      logo位置    -->
      <div style="display: flex; justify-content: center; text-align: center; align-items: center; margin-top: 10px;
        font-size: 1.2em; color: white; font-weight: normal; text-shadow: 2px 2px 4px rgba(0,0,0,1)">
        <div>
          <img src="../../assets/image/common/logo.png" style="width:40px; filter: brightness(1.5); height: auto; margin-top: 5px;">
        </div>
        <div>
          <span style="margin-left: 6px" class="title">金玥智阅</span>
        </div>
      </div>

      <!--      重置密码框-->
      <div :style="loginBoxStyle" class="login-box" style="opacity: 0.8; width: 350px; height: 410px;
      background-color: #555555; border-radius: 10px;  padding: 15px 50px; position: fixed">
        <div>
          <div style="margin: 0 0 15px 0; text-align: center; font-size: 30px; font-weight: bold; color: white">重置密码</div>
          <!-- 收缩/展开按钮 -->
          <div style=" position: absolute; top:30px ; right: 5px;  cursor: pointer; color: aqua; font-size: 15px;" @click="toggleLoginBox">
            <span :class="['rotate-icon', { rotate: !isLoginBoxExpanded }]">
               '▼'  <!-- 美观的箭头 -->
            </span>
          </div>
        </div>
        <el-form :model="user" ref="forgotPasswordForm" :rules="rules">
          <el-form-item prop="username">
            <el-input placeholder="请输入用户名" prefix-icon="el-icon-user" size="medium" v-model="user.username" ></el-input>
          </el-form-item>
          <el-form-item prop="password">
            <el-input placeholder="请输入密码" show-password prefix-icon="el-icon-lock" size="medium" v-model="user.password"></el-input>
          </el-form-item>
          <el-form-item prop="confirmPassword">
            <el-input placeholder="请确认密码" show-password prefix-icon="el-icon-lock" size="medium" v-model="user.confirmPassword"></el-input>
          </el-form-item>
          <el-form-item prop="email" style="display: flex; align-items: center;">
            <div style="flex: 1; display: flex; align-items: center">
              <el-input placeholder="请输入QQ邮箱" prefix-icon="el-icon-message" size="medium" v-model="user.email" style="width: 200px; ">
              </el-input>
              <el-button @click="sendCaptcha" type="primary" style="margin-left: 10px; padding: 8px; background-color: #67C23A" :disabled="!show">
                <span v-show="show">发送</span>
                <span v-show="!show">{{ count }} 秒后重发</span>
              </el-button>
            </div>
          </el-form-item>
          <el-form-item prop="emailCode">
            <el-input placeholder="请输入验证码" prefix-icon="el-icon-s-check" size="medium" v-model="user.emailCode"></el-input>
          </el-form-item>
          <el-form-item>
            <el-button class="custom-login-button" size="medium" type="primary" @click="confirm">重置</el-button>
            <el-button style="width: 30%; " size="medium" type="text" @click="skip">返回登陆页面</el-button>
          </el-form-item>
        </el-form>
      </div>
    </div>
    <!-- 加载指示器 -->
    <div v-if="loading" style="position: fixed; top: 50%; left: 50%; transform: translate(-50%, -50%); text-align: center; z-index: 9999;">
      <div style="font-size: 1.5em; color: #545c64;">玩命发送中...</div>
      <el-spinner></el-spinner> <!-- 这里使用 Element UI 的加载指示器 -->
    </div>
  </div>

</template>

<script>
import request from "@/utils/userRequest";
import Cookies from 'js-cookie';

const TIME_COUNT = 120 // 设置一个全局的倒计时的时间
const background = require("@/assets/image/login/login-background.jpg");

export default {
  username: 'forgetPassword',
  data() {
    return {
      isLoginBoxExpanded: true, // 控制登录框展开/收缩状态
      loginBoxHeightExpanded: '410px', // 展开时的高度
      loginBoxHeightCollapsed: '70px', // 收缩时的高度（仅显示标题部分）

      // 背景图片设置
      background: {
        backgroundImage: "url(" + background + ")",
        backgroundSize: "cover",
        backgroundPosition: "center",
        backgroundRepeat: "no-repeat",
      },
      show: true,
      timer: null,
      loading: false,
      count: '',
      user: {
        email: '',
        username: '',
        password: '',
        confirmPassword: '',
        emailCode: '',
      },
      rules: {
        username: [{required: true, message: '请输入用户名', trigger: 'blur'},
          {validator: this.checkName, trigger: 'blur'}],
        password: [{required: true, message: '请输入密码', trigger: 'blur'},
          {pattern: /^(?=.*[a-z])(?=.*[A-Z])[a-zA-Z\d]{8,16}$/,
            message: '密码必须为8-16位，且包含大小写字母', trigger: 'blur' }],
        emailCode: [{required: true, message: '请输入验证码', trigger: 'blur'},],
        email: [{required: true, message: '请输入邮箱', trigger: 'blur'},],
        confirmPassword: [{required: true, message: '请输入确认密码', trigger: 'blur'},
          { validator: this.validateConfirmPassword, trigger: 'blur' }  ],
      },
    }
  },

  computed: {
    loginBoxStyle() {
      return {
        opacity: 0.7,
        width: '350px',
        height: this.isLoginBoxExpanded ? this.loginBoxHeightExpanded : this.loginBoxHeightCollapsed,
        backgroundColor: '#545c64',
        borderRadius: '10px',
        margin: '130px 0 0 150px',
        padding: '20px 50px',
        position: 'fixed',
        overflow: 'hidden' // 当收缩时隐藏多余内容
      };
    },
  },

  methods: {
    // 用户名检验
    async checkName(rule, value, callback) {
      if(!value) return callback(new Error('用户名不能为空'))
      if(value.length < 2 || value.length > 10) return callback(new Error('用户名长度限制为3-10个字符'))
      try {
        const res = await request.get('/login/checkName', { params: { username: value } });
        if (res.data === true) {
          callback(new Error('用户名已存在'));
        } else {
          callback(); // 校验通过
        }
      } catch (error) {
        console.error(error);
        callback(new Error('无法验证用户名，请稍后重试'));
      }
    },
    // 转到登陆页面
    skip() {
      this.$router.push("/login")
    },
    // 判断密码与确认密码
    validateConfirmPassword(rule, value, callback) {
      if(value === '') {
        callback(new Error("请输入密码"))
      }
      else if(value !== this.user.password) {
        callback(new Error("密码不一致"))
      }
      else {
        callback()
      }
    },
    toggleLoginBox() {
      this.isLoginBoxExpanded = !this.isLoginBoxExpanded;  // true和false来回切换
    },
    sendCaptcha() {          // 发送邮箱
      const regexMail = /^[a-zA-Z0-9_-]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$/
      if(this.user.email === '') {
        this.$message.warning("请输入邮箱!")
      }
      else if (!regexMail.test(this.user.email)) {
        this.$message.warning('请输入正确的邮箱!')
      }
      else {
        this.loading = true; // 设置加载状态为 true
        request.post('login/sendEmail?tos=' + this.user.email).then(res => {
          this.loading = false; // 请求完成后，设置加载状态为 false
          if (res.code === 200) {
            Cookies.set('ifSendEmailCaptcha', 'true');
            this.$message.success("发送成功!");
          } else {
            this.$message.error(res.msg)
          }
        }).catch(err => {
          this.loading = false; // 处理请求错误
          this.$message.error("请求失败，请重试");
        });
        // 验证码倒计时
        if (!this.timer) {
          this.count = TIME_COUNT
          this.show = false
          this.timer = setInterval(() => {
            if (this.count > 0 && this.count <= TIME_COUNT) {
              this.count--
            }
            else {
              this.$message.warning("请重新发送QQ邮箱!")
              Cookies.set('ifSendEmailCaptcha', 'false')
              this.show = true
              clearInterval(this.timer)
              this.timer = null
            }
          }, 1000)
        }
      }
    },
    register() {  // 注册用户
      this.$refs['forgotPasswordForm'].validate((valid) => {
        if (valid) {
          const ifSendEmailCaptcha = Cookies.get("ifSendEmailCaptcha")
          if(ifSendEmailCaptcha === 'true') {
            request.post('login/userRegister', this.user).then(res => {
              if(res.code === 200) {
                this.$message.success('注册成功!')
                Cookies.remove('ifSendEmailCaptcha')
                clearInterval(this.timer)
                this.timer = null
                this.$router.push('/login')
              }
              else {
                this.$message.error(res.msg)
              }
            })
          }
          else {
            clearInterval(this.timer)
            this.timer = null
            this.$message.error("请重新填写信息！")
          }
        }
      })
    },
    confirm() {      // 修改密码
      this.$refs['forgotPasswordForm'].validate((valid) => {
        if (valid) {
          const ifSendEmailCaptcha = Cookies.get("ifSendEmailCaptcha")
          if(ifSendEmailCaptcha === 'true') {
            request.post('login/setNewPassword', this.user).then(res => {
              if(res.code === 200) {
                this.$message.success('密码修改成功!')
                Cookies.remove('ifSendEmailCaptcha')
                clearInterval(this.timer)
                this.timer = null
                this.$router.push('/login')
              }
              else {
                this.$message.error(res.msg)
              }
            })
          }
          else {
            clearInterval(this.timer)
            this.timer = null
            this.$message.error("请重新填写信息！")
          }
        }
      })
    },

  }
}
</script>

<style scoped>
.login-box {
  transition: height 0.8s ease-in-out; /* 添加动画效果 */
}
.rotate-icon {
  display: inline-block;
  transition: transform 0.8s ease;
}

.rotate-icon.rotate {
  transform: rotate(90deg);
}

.custom-login-button {
  background-color: #545c64;
  width: 60%;
  color: white;
  font-weight: bolder;
  font-size: large;
}

/* 设置 hover 颜色 */
.custom-login-button:hover {
  background-color: #6b737a; /* 设置鼠标悬停时的背景色 */
  color: #ffffff; /* 设置悬停时的文字颜色 */
}
</style>



